import tkinter as tk
from tkinter import ttk, messagebox
import time
import random
from generator import DatasetGenerator
import sys

# 检查必要的依赖库
try:
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import numpy as np
    
    # 设置matplotlib支持中文显示
    plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'KaiTi', 'FangSong', 'SimSun']  # 中文字体
    plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题
    
except ImportError:
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口
    
    error_msg = """缺少必要的依赖库！

本程序需要以下Python库：
- matplotlib
- numpy

请使用以下命令安装缺失的库：
pip install matplotlib numpy

安装完成后重新运行程序。"""
    
    messagebox.showerror("依赖错误", error_msg)
    print(error_msg)
    sys.exit(1)

from alg import SortingAlgorithms, insertion_sort

class SortingAlgorithmUI:
    def __init__(self, root):
        self.root = root
        self.root.title("排序算法可视化与对比")
        self.root.geometry("1200x800")
        self.root.configure(bg="#f0f0f0")
        
        # 设置程序图标
        try:
            self.root.iconbitmap("icon.ico")  # 如果有图标文件可以设置
        except:
            pass  # 如果没有图标文件则忽略
        
        self.generator = DatasetGenerator()
        self.sorting_algs = SortingAlgorithms()
        
        # 配置风格
        self.style = ttk.Style()
        self.style.configure('TFrame', background='#f0f0f0')
        self.style.configure('TButton', font=('Microsoft YaHei', 10))
        self.style.configure('TLabel', font=('Microsoft YaHei', 10))
        
        # 添加归并排序到算法列表
        self.algorithms = {
            "冒泡排序": self.sorting_algs.bubble_sort,
            "插入排序": insertion_sort,
            "快速排序": self.sorting_algs.quick_sort,
            "堆排序": self.sorting_algs.heap_sort,
            "归并排序": self.sorting_algs.merge_sort  # 新增的归并排序
        }
        
        # 添加归并排序的算法信息
        self.algorithm_info = {
            "冒泡排序": {
                "best_case": "O(n)",
                "avg_case": "O(n²)",
                "worst_case": "O(n²)",
                "space_complexity": "O(1)",
                "description": "冒泡排序是一种简单的排序算法，它重复地遍历要排序的数列，一次比较两个元素，如果它们的顺序错误就交换过来。"
            },
            "插入排序": {
                "best_case": "O(n)",
                "avg_case": "O(n²)",
                "worst_case": "O(n²)",
                "space_complexity": "O(1)",
                "description": "插入排序通过构建有序序列，对未排序数据，在已排序序列中从后向前扫描，找到相应位置并插入。"
            },
            "快速排序": {
                "best_case": "O(n log n)",
                "avg_case": "O(n log n)",
                "worst_case": "O(n²)",
                "space_complexity": "O(log n)",
                "description": "快速排序使用分治法策略来把一个序列分为较小和较大的2个子序列，然后递归地排序两个子序列。"
            },
            "堆排序": {
                "best_case": "O(n log n)",
                "avg_case": "O(n log n)",
                "worst_case": "O(n log n)",
                "space_complexity": "O(1)",
                "description": "堆排序是指利用堆这种数据结构所设计的一种排序算法。堆是一个近似完全二叉树的结构，并同时满足堆的性质：父节点的值总是大于或等于（小于或等于）子节点的值。"
            },
            "归并排序": {  # 归并排序的算法信息
                "best_case": "O(n log n)",
                "avg_case": "O(n log n)",
                "worst_case": "O(n log n)",
                "space_complexity": "O(n)",
                "description": "归并排序是一种分治算法，它将数组分成两个半部分，对每部分递归地应用归并排序，然后合并两个已排序的半部分。归并排序在任何情况下的时间复杂度都是O(n log n)，但需要额外的空间来存储临时数组。"
            }
        }
        
        self.current_algorithm = None
        self.dataset_sizes = [100, 500, 1000, 5000, 10000]
        self.dataset_types = ["随机", "已排序", "逆序", "部分有序"]
        
        # 添加归并排序的颜色
        self.chart_colors = {
            "冒泡排序": "#3498db",
            "插入排序": "#2ecc71",
            "快速排序": "#e74c3c",
            "堆排序": "#f39c12",
            "归并排序": "#9b59b6"  # 添加紫色作为归并排序的颜色
        }
        
        self.create_widgets()
        
        # 显示欢迎信息
        self.show_welcome_message()
    
    def show_welcome_message(self):
        """显示欢迎信息和使用指南"""
        self.result_text.delete(1.0, tk.END)
        welcome_text = """欢迎使用排序算法可视化与对比工具!

使用说明:
1. 从左侧控制面板选择排序算法
2. 选择数据大小和数据类型
3. 点击"运行单个算法"查看所选算法的性能
4. 点击"运行所有算法对比"比较不同算法的效率
5. 点击"查看算法详情"了解算法原理

图表说明:
- 上方图表显示算法执行时间对比
- 下方图表显示排序前和排序后的数据可视化

祝您使用愉快!
"""
        self.result_text.insert(tk.END, welcome_text)
    
    def create_widgets(self):
        # 主分割窗口
        self.paned_window = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
        self.paned_window.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 左侧控制面板
        control_frame = ttk.LabelFrame(self.paned_window, text="控制面板", padding="10")
        
        # 算法选择部分 - 使用彩色按钮代替单选按钮，更直观
        alg_select_frame = ttk.LabelFrame(control_frame, text="选择排序算法")
        alg_select_frame.pack(fill=tk.X, pady=10, padx=5)
        
        self.algorithm_var = tk.StringVar(value="冒泡排序")
        
        # 使用按钮样式的选择器
        for algorithm, color in self.chart_colors.items():
            btn = ttk.Button(
                alg_select_frame, 
                text=algorithm,
                command=lambda a=algorithm: self.select_algorithm(a)
            )
            btn.pack(fill=tk.X, pady=5)
        
        # 数据大小选择 - 使用下拉菜单代替大量单选按钮
        size_frame = ttk.LabelFrame(control_frame, text="数据大小")
        size_frame.pack(fill=tk.X, pady=10, padx=5)
        
        self.size_var = tk.IntVar(value=1000)
        size_dropdown = ttk.Combobox(
            size_frame, 
            textvariable=self.size_var, 
            values=self.dataset_sizes,
            state="readonly"
        )
        size_dropdown.pack(fill=tk.X, pady=5)
        
        # 数据类型选择
        type_frame = ttk.LabelFrame(control_frame, text="数据类型")
        type_frame.pack(fill=tk.X, pady=10, padx=5)
        
        self.type_var = tk.StringVar(value="随机")
        for data_type in self.dataset_types:
            ttk.Radiobutton(
                type_frame, 
                text=data_type, 
                value=data_type, 
                variable=self.type_var
            ).pack(anchor=tk.W, padx=10, pady=2)
        
        # 功能按钮 - 使用更明显的颜色和图标
        button_frame = ttk.Frame(control_frame)
        button_frame.pack(fill=tk.X, pady=20, padx=5)
        
        # 运行单个算法按钮
        single_btn = ttk.Button(
            button_frame, 
            text="▶ 运行单个算法", 
            command=self.run_single_algorithm
        )
        single_btn.pack(fill=tk.X, pady=5)
        
        # 运行所有算法按钮
        all_btn = ttk.Button(
            button_frame, 
            text="⟲ 运行所有算法对比", 
            command=self.run_all_algorithms
        )
        all_btn.pack(fill=tk.X, pady=5)
        
        # 查看详情按钮
        details_btn = ttk.Button(
            button_frame, 
            text="ℹ 查看算法详情", 
            command=self.show_algorithm_details
        )
        details_btn.pack(fill=tk.X, pady=5)
        
        # 导出结果按钮
        export_btn = ttk.Button(
            button_frame, 
            text="⤓ 导出结果", 
            command=self.export_results
        )
        export_btn.pack(fill=tk.X, pady=5)
        
        # 将控制面板添加到分割窗口
        self.paned_window.add(control_frame, weight=1)
        
        # 右侧结果显示区域
        result_frame = ttk.Frame(self.paned_window)
        self.paned_window.add(result_frame, weight=3)
        
        # 结果标题栏
        title_frame = ttk.Frame(result_frame)
        title_frame.pack(fill=tk.X, pady=10)
        
        self.result_title = ttk.Label(
            title_frame, 
            text="排序算法可视化分析",
            font=("Microsoft YaHei", 16, "bold")
        )
        self.result_title.pack(side=tk.LEFT)
        
        # 当前状态显示
        self.status_var = tk.StringVar(value="就绪")
        self.status_label = ttk.Label(
            title_frame,
            textvariable=self.status_var,
            font=("Microsoft YaHei", 10)
        )
        self.status_label.pack(side=tk.RIGHT, padx=10)
        
        # 创建选项卡控件
        notebook = ttk.Notebook(result_frame)
        notebook.pack(fill=tk.BOTH, expand=True, pady=5)
        
        # 性能对比选项卡
        performance_tab = ttk.Frame(notebook)
        notebook.add(performance_tab, text="性能对比")
        
        # 图表显示区域
        self.fig = plt.Figure(figsize=(8, 4), dpi=100)
        self.canvas = FigureCanvasTkAgg(self.fig, master=performance_tab)
        self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 数据可视化选项卡
        viz_tab = ttk.Frame(notebook)
        notebook.add(viz_tab, text="数据可视化")
        
        self.viz_fig = plt.Figure(figsize=(8, 4), dpi=100)
        self.viz_canvas = FigureCanvasTkAgg(self.viz_fig, master=viz_tab)
        self.viz_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 结果文本选项卡
        text_tab = ttk.Frame(notebook)
        notebook.add(text_tab, text="详细结果")
        
        # 结果文本显示
        self.result_text = tk.Text(text_tab, wrap=tk.WORD, font=("Consolas", 10))
        self.result_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 添加滚动条
        text_scrollbar = ttk.Scrollbar(self.result_text, orient="vertical", command=self.result_text.yview)
        text_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.result_text.configure(yscrollcommand=text_scrollbar.set)
    
    def select_algorithm(self, algorithm):
        """选择算法并更新界面"""
        self.algorithm_var.set(algorithm)
        self.status_var.set(f"已选择: {algorithm}")
    
    def generate_data(self):
        size = self.size_var.get()
        data_type = self.type_var.get()
        
        # 显示生成数据的状态
        self.status_var.set(f"生成{data_type}数据 ({size}元素)...")
        self.root.update()  # 更新界面
        
        if data_type == "随机":
            return self.generator.generate(size)
        elif data_type == "已排序":
            return self.generator.generate_sorted(size)
        elif data_type == "逆序":
            return self.generator.generate_reversed(size)
        elif data_type == "部分有序":
            return self.generator.generate_partially_sorted(size)
    
    def run_single_algorithm(self):
        algorithm_name = self.algorithm_var.get()
        algorithm = self.algorithms[algorithm_name]
        
        # 更新状态
        self.status_var.set(f"运行中: {algorithm_name}...")
        self.root.update()  # 更新界面
        
        data = self.generate_data()
        data_type = self.type_var.get()
        data_size = self.size_var.get()
        
        self.result_title.config(text=f"{algorithm_name} ({data_type}数据, {data_size}元素)")
        self.result_text.delete(1.0, tk.END)
        
        # 显示原始数据样本
        self.result_text.insert(tk.END, f"原始数据 (前10个): {data[:10]}\n\n")
        
        # 运行排序算法并计时 - 使用高精度计时器
        start_time = time.perf_counter()  # 更换为高精度计时器
        sorted_data = algorithm(data)
        end_time = time.perf_counter()    # 更换为高精度计时器
        
        execution_time = end_time - start_time
        
        # 防止出现0秒的情况，确保执行时间有意义
        if execution_time < 0.000001:
            execution_time = 0.000001
            
        # 显示排序后数据样本
        self.result_text.insert(tk.END, f"排序后数据 (前10个): {sorted_data[:10]}\n\n")
        
        # 验证排序结果
        is_sorted = all(sorted_data[i] <= sorted_data[i+1] for i in range(len(sorted_data)-1))
        self.result_text.insert(tk.END, f"排序结果正确: {'✓ 是' if is_sorted else '✗ 否'}\n")
        
        # 显示毫秒级时间更直观
        if execution_time < 0.1:
            time_str = f"{execution_time*1000:.3f} 毫秒"
        else:
            time_str = f"{execution_time:.6f} 秒"
            
        self.result_text.insert(tk.END, f"运行时间: {time_str}\n")
        
        # 可视化单个算法的性能
        self.plot_single_performance(algorithm_name, execution_time)
        
        # 可视化原始数据和排序后的数据
        self.visualize_data(data, sorted_data)
        
        # 更新状态 - 同样以毫秒显示
        if execution_time < 0.1:
            self.status_var.set(f"完成: {algorithm_name}, {execution_time*1000:.3f}毫秒")
        else:
            self.status_var.set(f"完成: {algorithm_name}, {execution_time:.6f}秒")
    
    def plot_single_performance(self, algorithm_name, execution_time):
        """绘制单个算法的性能图表"""
        # 清除旧图表
        self.fig.clear()
        
        # 创建新的条形图
        ax = self.fig.add_subplot(111)
        
        # 设置颜色
        color = self.chart_colors[algorithm_name]
        
        # 绘制柱状图
        bar = ax.bar([algorithm_name], [execution_time], color=color)
        
        # 添加数据标签 - 针对不同时间大小采用不同显示方式
        if execution_time < 0.1:
            time_str = f'{execution_time*1000:.3f}毫秒'
        else:
            time_str = f'{execution_time:.6f}秒'
            
        ax.text(0, execution_time, time_str,
                ha='center', va='bottom', fontsize=12)
        
        # 设置标题和标签
        ax.set_ylabel('执行时间（秒）', fontsize=12)
        ax.set_title(f'{algorithm_name} 排序性能', fontsize=14)
        ax.tick_params(axis='x', labelsize=12)
        ax.tick_params(axis='y', labelsize=10)
        
        # 设置Y轴从0开始，并确保即使时间很小也能看到柱状图
        min_height = 0.000001 if execution_time < 0.000001 else 0
        ax.set_ylim(min_height, execution_time * 1.5)  # 增加上限，使小值也能看到
        
        # 对于非常小的值，添加注释
        if execution_time < 0.001:
            ax.annotate('执行时间非常短!', xy=(0, execution_time/2),
                       xytext=(0.5, 0.5), textcoords='axes fraction',
                       arrowprops=dict(arrowstyle="->", connectionstyle="arc3"),
                       ha='center', bbox=dict(boxstyle="round,pad=0.3", fc="yellow", alpha=0.8))
        
        # 添加网格线以便于阅读
        ax.grid(axis='y', linestyle='--', alpha=0.7)
        
        # 使用对数刻度，能更好地表示小值
        if execution_time < 0.001:
            ax.set_yscale('log')
            ax.set_ylabel('执行时间（对数刻度，秒）', fontsize=12)
        
        self.fig.tight_layout()
        self.canvas.draw()
    
    def run_all_algorithms(self):
        data = self.generate_data()
        data_type = self.type_var.get()
        data_size = self.size_var.get()
        
        self.status_var.set("运行所有排序算法对比...")
        self.root.update()  # 更新界面
        
        self.result_title.config(text=f"排序算法性能对比 ({data_type}数据, {data_size}元素)")
        self.result_text.delete(1.0, tk.END)
        
        results = []
        
        # 运行所有算法并记录结果
        for name, algorithm in self.algorithms.items():
            # 更新状态
            self.status_var.set(f"运行中: {name}...")
            self.root.update()
            
            # 使用数据副本以确保每个算法排序相同的数据
            test_data = data.copy()
            
            # 计时 - 使用高精度计时器
            start_time = time.perf_counter()  # 更换为高精度计时器
            sorted_data = algorithm(test_data)
            end_time = time.perf_counter()    # 更换为高精度计时器
            
            execution_time = end_time - start_time
            
            # 防止出现0秒的情况
            if execution_time < 0.000001:
                execution_time = 0.000001
            
            # 验证排序结果
            is_sorted = all(sorted_data[i] <= sorted_data[i+1] for i in range(len(sorted_data)-1))
            
            results.append({
                'name': name,
                'time': execution_time,
                'sorted': is_sorted,
                'color': self.chart_colors[name]
            })
            
            # 显示毫秒级时间更直观
            if execution_time < 0.1:
                time_str = f"{execution_time*1000:.3f} 毫秒"
            else:
                time_str = f"{execution_time:.6f} 秒"
                
            self.result_text.insert(tk.END, f"{name}: {time_str}, 排序{'✓ 正确' if is_sorted else '✗ 错误'}\n")
        
        # 按性能排序结果
        results.sort(key=lambda x: x['time'])
        
        # 显示排名
        for i, result in enumerate(results):
            self.result_text.insert(tk.END, f"第{i+1}名: {result['name']} - {result['time']:.6f}秒\n")
        
        # 绘制性能对比图
        self.plot_comparison(results)
        
        # 可视化排序前后的数据（使用最后一个算法的结果）
        if results:
            self.visualize_data(data, sorted_data)
            
        # 显示详细的图表和分析结果
        self.show_detailed_results(results, sorted_data, data)
        
        # 更新状态
        self.status_var.set("对比完成!")
    
    def plot_comparison(self, results):
        # 清除旧图表
        self.fig.clear()
        
        # 创建新的条形图
        ax = self.fig.add_subplot(111)
        
        names = [result['name'] for result in results]
        times = [result['time'] for result in results]
        colors = [result['color'] for result in results]
        
        # 绘制柱状图
        bars = ax.bar(names, times, color=colors)
        
        # 添加数据标签 - 使用毫秒显示小值
        for bar in bars:
            height = bar.get_height()
            if height < 0.1:
                time_str = f'{height*1000:.3f}ms'
            else:
                time_str = f'{height:.6f}s'
                
            ax.text(bar.get_x() + bar.get_width()/2., height,
                    time_str,
                    ha='center', va='bottom', fontsize=11)
        
        # 设置标签和标题
        ax.set_ylabel('执行时间（秒）', fontsize=12)
        ax.set_title('排序算法性能对比', fontsize=14)
        ax.tick_params(axis='x', labelsize=12, rotation=0)
        ax.tick_params(axis='y', labelsize=10)
        
        # 确保Y轴有合理的范围，使小值也能看到
        min_time = min(times)
        max_time = max(times)
        
        # 如果所有时间都很小，使用对数刻度
        if max_time < 0.001:
            ax.set_yscale('log')
            ax.set_ylabel('执行时间（对数刻度，秒）', fontsize=12)
        elif max_time/min_time > 100:  # 如果时间差异很大
            ax.set_yscale('log')
            ax.set_ylabel('执行时间（对数刻度，秒）', fontsize=12)
        
        # 添加网格线以便于阅读
        ax.grid(axis='y', linestyle='--', alpha=0.7)
        
        self.fig.tight_layout()
        self.canvas.draw()
    
    def visualize_data(self, original_data, sorted_data):
        # 最多显示100个元素以确保可视化清晰
        display_limit = min(100, len(original_data))
        
        # 清除旧图表
        self.viz_fig.clear()
        
        # 创建子图
        original_ax = self.viz_fig.add_subplot(121)
        sorted_ax = self.viz_fig.add_subplot(122)
        
        # 绘制原始数据
        original_ax.bar(range(display_limit), original_data[:display_limit], color='#3498db')
        original_ax.set_title('原始数据', fontsize=12)
        original_ax.set_xticks([])
        
        # 添加统计信息
        original_stats = f"均值: {np.mean(original_data):.2f}\n标准差: {np.std(original_data):.2f}"
        original_ax.text(0.5, 0.95, original_stats, transform=original_ax.transAxes, 
                        ha='center', va='top', fontsize=9, bbox=dict(boxstyle="round,pad=0.3", fc="white", alpha=0.8))
        
        # 绘制排序后的数据
        sorted_ax.bar(range(display_limit), sorted_data[:display_limit], color='#2ecc71')
        sorted_ax.set_title('排序后数据', fontsize=12)
        sorted_ax.set_xticks([])
        
        # 添加统计信息
        sorted_stats = f"均值: {np.mean(sorted_data):.2f}\n标准差: {np.std(sorted_data):.2f}"
        sorted_ax.text(0.5, 0.95, sorted_stats, transform=sorted_ax.transAxes, 
                     ha='center', va='top', fontsize=9, bbox=dict(boxstyle="round,pad=0.3", fc="white", alpha=0.8))
        
        self.viz_fig.tight_layout()
        self.viz_canvas.draw()
    
    def show_algorithm_details(self):
        algorithm_name = self.algorithm_var.get()
        info = self.algorithm_info[algorithm_name]
        
        # 创建一个新窗口显示详细信息
        details_window = tk.Toplevel(self.root)
        details_window.title(f"{algorithm_name} - 详细信息")
        details_window.geometry("720x550")  # 增加窗口大小
        details_window.transient(self.root)  # 设置为主窗口的子窗口
        details_window.grab_set()  # 模态窗口
        
        # 创建主滚动区域
        main_canvas = tk.Canvas(details_window)
        main_canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        # 为Canvas添加滚动条
        main_scrollbar = ttk.Scrollbar(details_window, orient=tk.VERTICAL, command=main_canvas.yview)
        main_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        main_canvas.configure(yscrollcommand=main_scrollbar.set)
        
        # 创建内容框架
        content_frame = ttk.Frame(main_canvas)
        main_canvas.create_window((0, 0), window=content_frame, anchor="nw", tags="content_frame")
        
        # 设置边距和样式
        padding_frame = ttk.Frame(content_frame, padding="20")
        padding_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题 - 添加漂亮的分隔线
        title_frame = ttk.Frame(padding_frame)
        title_frame.pack(fill=tk.X, pady=(0, 15))
        
        ttk.Label(
            title_frame, 
            text=algorithm_name,
            font=("Microsoft YaHei", 18, "bold")
        ).pack(anchor=tk.W)
        
        ttk.Separator(title_frame).pack(fill=tk.X, pady=10)
        
        # 算法描述区域 - 使用更好的框架和边框
        desc_frame = ttk.LabelFrame(padding_frame, text="算法描述")
        desc_frame.pack(fill=tk.X, pady=10)
        
        desc_text = tk.Text(desc_frame, height=5, wrap=tk.WORD, font=("Microsoft YaHei", 10))
        desc_text.insert(tk.END, info['description'])
        desc_text.config(state=tk.DISABLED, bd=0, highlightthickness=0)
        desc_text.pack(fill=tk.X, padx=10, pady=10)
        
        # 复杂度信息 - 使用更现代的布局
        complexity_frame = ttk.LabelFrame(padding_frame, text="算法复杂度")
        complexity_frame.pack(fill=tk.X, pady=10)
        
        # 时间和空间复杂度放在同一行
        comp_inner_frame = ttk.Frame(complexity_frame)
        comp_inner_frame.pack(fill=tk.X, padx=10, pady=10)
        
        # 左侧：时间复杂度
        time_frame = ttk.Frame(comp_inner_frame)
        time_frame.pack(side=tk.LEFT, fill=tk.Y)
        
        ttk.Label(time_frame, text="时间复杂度", font=("Microsoft YaHei", 11, "bold")).pack(anchor=tk.W, pady=(0,5))
        ttk.Label(time_frame, text=f"• 最佳情况: {info['best_case']}", font=("Microsoft YaHei", 10)).pack(anchor=tk.W, pady=2)
        ttk.Label(time_frame, text=f"• 平均情况: {info['avg_case']}", font=("Microsoft YaHei", 10)).pack(anchor=tk.W, pady=2)
        ttk.Label(time_frame, text=f"• 最差情况: {info['worst_case']}", font=("Microsoft YaHei", 10)).pack(anchor=tk.W, pady=2)
        
        # 添加分隔符
        ttk.Separator(comp_inner_frame, orient=tk.VERTICAL).pack(side=tk.LEFT, fill=tk.Y, padx=20, pady=5)
        
        # 右侧：空间复杂度
        space_frame = ttk.Frame(comp_inner_frame)
        space_frame.pack(side=tk.LEFT, fill=tk.Y)
        
        ttk.Label(space_frame, text="空间复杂度", font=("Microsoft YaHei", 11, "bold")).pack(anchor=tk.W, pady=(0,5))
        ttk.Label(space_frame, text=f"• 辅助空间: {info['space_complexity']}", font=("Microsoft YaHei", 10)).pack(anchor=tk.W, pady=2)
        
        # 算法伪代码或说明 - 使用更好的代码显示
        if algorithm_name == "冒泡排序":
            code = """procedure bubbleSort(A : list of sortable items)
    n := length(A)
    repeat
        swapped := false
        for i := 1 to n-1 inclusive do
            if A[i-1] > A[i] then
                swap(A[i-1], A[i])
                swapped := true
            end if
        end for
        n := n - 1
    until not swapped
end procedure"""
        elif algorithm_name == "插入排序":
            code = """procedure insertionSort(A : array of items)
    for i from 1 to length(A)
        j := i
        while j > 0 and A[j-1] > A[j]
            swap A[j] and A[j-1]
            j := j - 1
        end while
    end for
end procedure"""
        elif algorithm_name == "快速排序":
            code = """procedure quickSort(A, lo, hi)
    if lo < hi then
        p := partition(A, lo, hi)
        quickSort(A, lo, p - 1)
        quickSort(A, p + 1, hi)
    end if
end procedure

procedure partition(A, lo, hi)
    pivot := A[hi]
    i := lo - 1
    for j from lo to hi - 1 do
        if A[j] <= pivot then
            i := i + 1
            swap A[i] with A[j]
        end if
    end for
    swap A[i+1] with A[hi]
    return i + 1
end procedure"""
        elif algorithm_name == "堆排序":
            code = """procedure heapSort(A)
    buildMaxHeap(A)
    for i from length(A) down to 2 do
        swap A[1] with A[i]
        heapSize := heapSize - 1
        maxHeapify(A, 1)
    end for
end procedure

procedure buildMaxHeap(A)
    heapSize := length(A)
    for i from floor(length(A)/2) down to 1 do
        maxHeapify(A, i)
    end for
end procedure"""
        elif algorithm_name == "归并排序":
            code = """procedure mergeSort(A, left, right)
    if left < right then
        middle = ⌊(left + right) / 2⌋
        mergeSort(A, left, middle)
        mergeSort(A, middle + 1, right)
        merge(A, left, middle, right)
    end if
end procedure

procedure merge(A, left, middle, right)
    // 创建临时数组存储合并结果
    let n1 = middle - left + 1
    let n2 = right - middle
    let L[1...n1] and R[1...n2] be new arrays
    
    for i from 1 to n1
        L[i] = A[left + i - 1]
    for j from 1 to n2
        R[j] = A[middle + j]
    
    i = 1
    j = 1
    k = left
    
    while i ≤ n1 and j ≤ n2 do
        if L[i] ≤ R[j] then
            A[k] = L[i]
            i = i + 1
        else
            A[k] = R[j]
            j = j + 1
        end if
        k = k + 1
    end while
    
    // 复制剩余元素
    while i ≤ n1 do
        A[k] = L[i]
        i = i + 1
        k = k + 1
    end while
    
    while j ≤ n2 do
        A[k] = R[j]
        j = j + 1
        k = k + 1
    end while
end procedure"""
        
        # 伪代码区域 - 使用更好看的代码框
        code_frame = ttk.LabelFrame(padding_frame, text="算法伪代码")
        code_frame.pack(fill=tk.BOTH, expand=True, pady=10)
        
        # 创建代码文本区域和滚动条框架
        code_text_frame = ttk.Frame(code_frame)
        code_text_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 创建具有语法高亮效果的文本显示
        code_text = tk.Text(code_text_frame, wrap=tk.NONE, font=("Consolas", 11),
                          bg="#f8f8f8", fg="#333333")
        code_text.insert(tk.END, code)
        
        # 简单的语法高亮 (关键字加粗)
        keywords = ['procedure', 'end', 'if', 'then', 'else', 'for', 'while', 'do', 'repeat', 'until']
        for keyword in keywords:
            start_idx = '1.0'
            while True:
                start_idx = code_text.search(keyword, start_idx, tk.END)
                if not start_idx:
                    break
                end_idx = f"{start_idx}+{len(keyword)}c"
                code_text.tag_add("keyword", start_idx, end_idx)
                start_idx = end_idx
                
        code_text.tag_configure("keyword", foreground="#0066cc", font=("Consolas", 11, "bold"))
        
        # 禁止编辑
        code_text.config(state=tk.DISABLED)
        code_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        # 添加滚动条
        code_v_scroll = ttk.Scrollbar(code_text_frame, orient=tk.VERTICAL, command=code_text.yview)
        code_v_scroll.pack(side=tk.RIGHT, fill=tk.Y)
        code_h_scroll = ttk.Scrollbar(code_frame, orient=tk.HORIZONTAL, command=code_text.xview)
        code_h_scroll.pack(side=tk.BOTTOM, fill=tk.X)
        
        code_text.configure(yscrollcommand=code_v_scroll.set, xscrollcommand=code_h_scroll.set)
        
        # 添加视觉元素分隔线
        ttk.Separator(padding_frame).pack(fill=tk.X, pady=10)
        
        # 按钮区域 - 美化按钮
        button_frame = ttk.Frame(padding_frame)
        button_frame.pack(fill=tk.X, pady=10)
        
        # 关闭按钮
        close_btn = ttk.Button(
            button_frame, 
            text="关闭窗口",
            command=details_window.destroy,
            style="Accent.TButton"  # 使用强调样式
        )
        close_btn.pack(side=tk.RIGHT)
        
        # 在Notebook中添加可视化示例标签页
        if False:  # 暂时不实现，可以后续扩展
            example_btn = ttk.Button(
                button_frame, 
                text="查看排序动画",
                command=lambda: self.show_sorting_animation(algorithm_name)
            )
            example_btn.pack(side=tk.LEFT)
        
        # 配置Canvas滚动区域
        content_frame.update_idletasks()  # 更新尺寸信息
        main_canvas.config(scrollregion=main_canvas.bbox("all"))
        main_canvas.bind("<Configure>", lambda e: main_canvas.itemconfig("content_frame", width=e.width))
        
        # 绑定鼠标滚轮事件
        details_window.bind("<MouseWheel>", lambda e: main_canvas.yview_scroll(int(-1*(e.delta/120)), "units"))
        details_window.bind("<Button-4>", lambda e: main_canvas.yview_scroll(-1, "units"))
        details_window.bind("<Button-5>", lambda e: main_canvas.yview_scroll(1, "units"))
        
        # 尝试创建一个强调按钮样式
        try:
            self.style.configure("Accent.TButton", font=("Microsoft YaHei", 10, "bold"))
            if hasattr(self.style, "map"):
                self.style.map("Accent.TButton",
                      foreground=[('pressed', '#ffffff'), ('active', '#ffffff')],
                      background=[('pressed', '#3366cc'), ('active', '#5588dd')])
        except:
            pass  # 如果样式设置失败，使用默认样式
    
    def export_results(self):
        """导出测试结果到文件"""
        try:
            from datetime import datetime
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"排序算法测试结果_{timestamp}.txt"
            
            with open(filename, "w", encoding="utf-8") as f:
                f.write("排序算法性能测试结果\n")
                f.write("=" * 40 + "\n\n")
                f.write(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write(f"数据类型: {self.type_var.get()}\n")
                f.write(f"数据大小: {self.size_var.get()}\n\n")
                f.write(self.result_text.get(1.0, tk.END))
            
            self.status_var.set(f"结果已导出至: {filename}")
            messagebox.showinfo("导出成功", f"测试结果已成功导出到:\n{filename}")
        except Exception as e:
            messagebox.showerror("导出失败", f"导出结果时出错:\n{str(e)}")
    
    def show_detailed_results(self, results=None, sorted_data=None, original_data=None):
        """显示更详细的结果分析和可视化图表"""
        # 如果未提供结果，则使用当前数据
        if not results:
            return
        
        # 添加处理中文对齐的辅助函数
        def get_display_width(text):
            """计算字符串的显示宽度，中文字符计为2个单位宽度"""
            width = 0
            for char in text:
                if ord(char) > 127:  # 中文和其他全角字符
                    width += 2
                else:
                    width += 1
            return width
        
        def align_text(text, width, align='left'):
            """对齐文本，考虑中文字符宽度"""
            text_width = get_display_width(text)
            padding = width - text_width
            if padding <= 0:
                return text
            
            if align == 'left':
                return text + ' ' * padding
            elif align == 'right':
                return ' ' * padding + text
            else:  # center
                left_padding = padding // 2
                right_padding = padding - left_padding
                return ' ' * left_padding + text + ' ' * right_padding
        
        # 清除现有文本
        self.result_text.delete(1.0, tk.END)
        
        # 设置文本标签样式
        self.result_text.tag_configure("title", font=("Microsoft YaHei", 14, "bold"), foreground="#3366cc")
        self.result_text.tag_configure("subtitle", font=("Microsoft YaHei", 12, "bold"), foreground="#333333")
        self.result_text.tag_configure("highlight", font=("Microsoft YaHei", 10, "bold"), foreground="#e74c3c")
        self.result_text.tag_configure("good", foreground="#2ecc71")
        self.result_text.tag_configure("bad", foreground="#e74c3c")
        self.result_text.tag_configure("normal", font=("Microsoft YaHei", 10))
        self.result_text.tag_configure("code", font=("Consolas", 10), background="#f5f5f5")
        
        # 添加精美的标题
        self.result_text.insert(tk.END, "排序算法性能测试报告\n", "title")
        self.result_text.insert(tk.END, "─" * 50 + "\n\n", "normal")
        
        # 测试环境信息
        self.result_text.insert(tk.END, "📊 测试环境\n", "subtitle")
        
        # 创建测试环境表格 - 修复对齐问题
        param_width = 15
        value_width = 30
        total_width = 48  # 总宽度
        
        env_table = "┌" + "─" * total_width + "┐\n"
        env_table += f"│ {align_text('参数', param_width)} │ {align_text('值', value_width)} │\n"
        env_table += "├" + "─" * (param_width + 2) + "┼" + "─" * (value_width + 2) + "┤\n"
        env_table += f"│ {align_text('数据类型', param_width)} │ {align_text(self.type_var.get(), value_width)} │\n"
        env_table += f"│ {align_text('数据大小', param_width)} │ {align_text(str(self.size_var.get()) + ' 元素', value_width)} │\n"
        
        import platform
        env_table += f"│ {align_text('系统环境', param_width)} │ {align_text(platform.system() + ' ' + platform.version(), value_width)} │\n"
        env_table += f"│ {align_text('Python版本', param_width)} │ {align_text(platform.python_version(), value_width)} │\n"
        env_table += "└" + "─" * (param_width + 2) + "┴" + "─" * (value_width + 2) + "┘\n"
        
        self.result_text.insert(tk.END, env_table, "code")
        self.result_text.insert(tk.END, "\n", "normal")
        
        # 排序结果
        self.result_text.insert(tk.END, "🏆 算法性能排名\n", "subtitle")
        
        # 对结果按执行时间排序
        results.sort(key=lambda x: x['time'])
        
        # 显示排名表格 - 修复对齐问题
        rank_width = 4
        alg_width = 10
        time_width = 15
        result_width = 6
        rel_width = 10
        
        result_table = "┌" + "─" * (rank_width + alg_width + time_width + result_width + rel_width + 10) + "┐\n"
        result_table += f"│ {align_text('排名', rank_width)} │ {align_text('算法名称', alg_width)} │ {align_text('执行时间', time_width)} │ {align_text('结果', result_width)} │ {align_text('相对性能', rel_width)} │\n"
        result_table += "├" + "─" * (rank_width + 2) + "┼" + "─" * (alg_width + 2) + "┼" + "─" * (time_width + 2) + "┼" + "─" * (result_width + 2) + "┼" + "─" * (rel_width + 2) + "┤\n"
        
        # 计算相对性能（最快算法为基准）
        fastest_time = results[0]['time']
        
        for i, result in enumerate(results):
            relative = f"{result['time']/fastest_time:.2f}x"
            if i == 0:
                relative = "基准 (1.00x)"
                
            time_str = f"{result['time']*1000:.3f} 毫秒" if result['time'] < 0.1 else f"{result['time']:.6f} 秒"
            result_mark = "✓" if result['sorted'] else "✗"
            
            result_table += f"│ {align_text(str(i+1), rank_width)} │ {align_text(result['name'], alg_width)} │ {align_text(time_str, time_width)} │ {align_text(result_mark, result_width)} │ {align_text(relative, rel_width)} │\n"
            
        result_table += "└" + "─" * (rank_width + 2) + "┴" + "─" * (alg_width + 2) + "┴" + "─" * (time_width + 2) + "┴" + "─" * (result_width + 2) + "┴" + "─" * (rel_width + 2) + "┘\n"
        
        self.result_text.insert(tk.END, result_table, "code")
        self.result_text.insert(tk.END, "\n", "normal")
        
        # 添加分析结论
        self.result_text.insert(tk.END, "🔍 分析结论\n", "subtitle")
        
        # 基于数据类型给出不同的结论
        data_type = self.type_var.get()
        fastest_alg = results[0]['name']
        slowest_alg = results[-1]['name']
        
        # 结论框 - 修复对齐问题
        inner_width = 46  # 内容宽度
        
        conclusion = "┌" + "─" * 48 + "┐\n"
        conclusion += "│ " + align_text("算法性能分析", inner_width) + " │\n"
        conclusion += "├" + "─" * 48 + "┤\n"
        
        if data_type == "随机":
            conclusion += "│ • " + align_text(f"对于随机数据，{fastest_alg}表现最佳", inner_width - 2) + " │\n"
            conclusion += "│ • " + align_text(f"{slowest_alg}速度最慢，是{fastest_alg}的{results[-1]['time']/results[0]['time']:.2f}倍", inner_width - 2) + " │\n"
            if "快速排序" in fastest_alg:
                conclusion += "│ • " + align_text("快速排序在随机数据上通常有最佳性能，这符合理论预期", inner_width - 2) + " │\n"
            elif "堆排序" in fastest_alg:
                conclusion += "│ • " + align_text("堆排序在大规模随机数据上表现稳定，这符合理论预期", inner_width - 2) + " │\n"
            else:
                conclusion += "│ • " + align_text(f"{fastest_alg}在本次测试中表现最佳", inner_width - 2) + " │\n"
                
        elif data_type == "已排序":
            conclusion += "│ • " + align_text(f"对于已排序数据，{fastest_alg}表现最佳", inner_width - 2) + " │\n"
            if "插入排序" in fastest_alg:
                conclusion += "│ • " + align_text("插入排序在已排序数据上接近O(n)复杂度，这符合理论预期", inner_width - 2) + " │\n"
            elif "冒泡排序" in fastest_alg:
                conclusion += "│ • " + align_text("冒泡排序在已排序数据上有优化机制，这符合理论预期", inner_width - 2) + " │\n"
            else:
                conclusion += "│ • " + align_text(f"{fastest_alg}在本次测试中表现最佳", inner_width - 2) + " │\n"
                
        elif data_type == "逆序":
            conclusion += "│ • " + align_text(f"对于逆序数据，{fastest_alg}表现最佳", inner_width - 2) + " │\n"
            if "快速排序" in slowest_alg:
                conclusion += "│ • " + align_text("快速排序在逆序数据上可能退化为O(n²)，这符合理论预期", inner_width - 2) + " │\n"
            else:
                conclusion += "│ • " + align_text(f"{fastest_alg}在本次测试中表现最佳", inner_width - 2) + " │\n"
        
        else:  # 部分有序
            conclusion += "│ • " + align_text(f"对于部分有序数据，{fastest_alg}表现最佳", inner_width - 2) + " │\n"
            conclusion += "│ • " + align_text(f"{fastest_alg}在部分有序数据上有更高的适应性", inner_width - 2) + " │\n"
            
        # 添加最佳算法推荐
        conclusion += "│ " + " " * inner_width + " │\n"
        conclusion += "│ " + align_text("📌 推荐算法:", inner_width) + " │\n"
        conclusion += "│ " + align_text(f"   {fastest_alg} - 在该数据类型上表现最佳", inner_width) + " │\n"
        conclusion += "└" + "─" * 48 + "┘\n"
        
        self.result_text.insert(tk.END, conclusion, "code")
        
        # 添加算法速度比较说明
        self.result_text.insert(tk.END, "\n📈 速度比较\n", "subtitle")
        perf_text = "以下是各算法相对于最快算法的性能比较：\n\n"
        self.result_text.insert(tk.END, perf_text, "normal")
        
        # 创建可视化的性能条形图 - 修复对齐问题
        name_width = 10  # 算法名称显示宽度
        for i, result in enumerate(results):
            alg_name = result['name']
            relative_time = result['time']/fastest_time
            bar_length = min(30, int(30 * relative_time))
            
            # 确保算法名称对齐
            displayed_name = align_text(alg_name, name_width)
            
            if i == 0:  # 最快的算法
                self.result_text.insert(tk.END, f"{displayed_name} │", "normal")
                self.result_text.insert(tk.END, "█" * bar_length, "good")
                self.result_text.insert(tk.END, f" {relative_time:.2f}x (最快)\n", "good")
            else:
                self.result_text.insert(tk.END, f"{displayed_name} │", "normal")
                if relative_time < 2:
                    self.result_text.insert(tk.END, "█" * bar_length, "normal")
                    self.result_text.insert(tk.END, f" {relative_time:.2f}x\n", "normal")
                else:
                    self.result_text.insert(tk.END, "█" * bar_length, "bad")
                    self.result_text.insert(tk.END, f" {relative_time:.2f}x\n", "bad")
        
        # 添加复杂度理论表 - 修复对齐问题
        self.result_text.insert(tk.END, "\n🧮 算法复杂度参考\n", "subtitle")
        
        alg_width = 10
        case_width = 10
        
        complexity_table = "┌" + "─" * 48 + "┐\n"
        complexity_table += f"│ {align_text('算法', alg_width)} │ {align_text('最佳情况', case_width)} │ {align_text('平均情况', case_width)} │ {align_text('最差情况', case_width)} │\n"
        complexity_table += "├" + "─" * (alg_width + 2) + "┼" + "─" * (case_width + 2) + "┼" + "─" * (case_width + 2) + "┼" + "─" * (case_width + 2) + "┤\n"
        
        for name in ["冒泡排序", "插入排序", "快速排序", "堆排序", "归并排序"]:
            info = self.algorithm_info[name]
            complexity_table += f"│ {align_text(name, alg_width)} │ {align_text(info['best_case'], case_width)} │ {align_text(info['avg_case'], case_width)} │ {align_text(info['worst_case'], case_width)} │\n"
            
        complexity_table += "└" + "─" * (alg_width + 2) + "┴" + "─" * (case_width + 2) + "┴" + "─" * (case_width + 2) + "┴" + "─" * (case_width + 2) + "┘\n"
        
        self.result_text.insert(tk.END, complexity_table, "code")
        
        # 添加图表提示
        self.result_text.insert(tk.END, "\n📊 详细图表\n", "subtitle")
        self.result_text.insert(tk.END, "请查看下方选项卡中的详细图表分析：\n", "normal")
        self.result_text.insert(tk.END, " • 性能比较：各算法执行时间的柱状图和折线图对比\n", "normal")
        self.result_text.insert(tk.END, " • 规模扩展性：预测不同数据规模下的算法性能\n", "normal")
        self.result_text.insert(tk.END, " • 数据分布：原始数据和排序后数据的分布可视化\n", "normal")
        
        # 创建性能图表选项卡
        self.create_performance_charts(results, original_data, sorted_data)

    def create_performance_charts(self, results, original_data, sorted_data):
        """创建性能图表"""
        # 在"详细结果"选项卡中添加一个笔记本控件用于显示多个图表
        for child in self.root.winfo_children():
            if isinstance(child, ttk.PanedWindow):
                for pane in child.panes():
                    for notebook in pane.winfo_children():
                        if isinstance(notebook, ttk.Notebook):
                            for tab in notebook.tabs():
                                tab_widget = notebook.nametowidget(tab)
                                if "详细结果" in notebook.tab(tab, "text"):
                                    # 找到了详细结果选项卡，现在创建图表
                                    # 在文本框下方添加图表区域
                                    charts_frame = ttk.LabelFrame(tab_widget, text="图表分析")
                                    charts_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
                                    
                                    # 创建子选项卡
                                    charts_notebook = ttk.Notebook(charts_frame)
                                    charts_notebook.pack(fill=tk.BOTH, expand=True)
                                    
                                    # 1. 算法性能比较图 - 美化版
                                    perf_tab = ttk.Frame(charts_notebook)
                                    charts_notebook.add(perf_tab, text="性能比较")
                                    
                                    fig1 = plt.Figure(figsize=(6, 4), dpi=100)
                                    ax1 = fig1.add_subplot(111)
                                    
                                    # 绘制柱状图和折线图组合
                                    names = [result['name'] for result in results]
                                    times = [result['time']*1000 if result['time'] < 0.1 else result['time'] 
                                            for result in results]
                                    colors = [result['color'] for result in results]
                                    
                                    # 设置漂亮的背景
                                    ax1.set_facecolor('#f8f9fa')
                                    fig1.patch.set_facecolor('#f8f9fa')
                                    
                                    # 柱状图 - 添加渐变效果
                                    bars = ax1.bar(names, times, color=colors, alpha=0.7)
                                    
                                    # 为柱状图添加微妙的阴影效果
                                    for bar in bars:
                                        bar.set_edgecolor('white')
                                        bar.set_linewidth(1)
                                    
                                    # 折线图和标记点
                                    ax1.plot(names, times, 'o-', color='#d63031', linewidth=2, markersize=8,
                                           markerfacecolor='white', markeredgewidth=2, markeredgecolor='#d63031')
                                    
                                    # 设置图表样式和标签
                                    if max(times) < 0.1:
                                        unit = "毫秒"
                                        display_times = [t*1000 for t in times]
                                    else:
                                        unit = "秒"
                                        display_times = times
                                    
                                    ax1.set_ylabel(f'执行时间（{unit}）', fontsize=12, fontweight='bold')
                                    ax1.set_title('排序算法性能对比', fontsize=16, fontweight='bold', pad=20)
                                    
                                    # 为每个柱添加标签
                                    for i, bar in enumerate(bars):
                                        height = bar.get_height()
                                        ax1.text(bar.get_x() + bar.get_width()/2., height + max(times)*0.02,
                                                f'{display_times[i]:.2f}',
                                                ha='center', va='bottom', fontsize=10, fontweight='bold')
                                    
                                    # 添加网格 - 使用虚线并降低不透明度使其不干扰主要数据
                                    ax1.yaxis.grid(True, linestyle='--', alpha=0.3)
                                    ax1.set_axisbelow(True)  # 确保网格在数据下方
                                    
                                    # 删除顶部和右侧边框
                                    ax1.spines['top'].set_visible(False)
                                    ax1.spines['right'].set_visible(False)
                                    ax1.spines['left'].set_color('#cccccc')
                                    ax1.spines['bottom'].set_color('#cccccc')
                                    
                                    # 添加堆叠条形图说明最快算法
                                    fastest_index = times.index(min(times))
                                    for i, bar in enumerate(bars):
                                        if i == fastest_index:
                                            bar.set_hatch('///')
                                            ax1.text(bar.get_x() + bar.get_width()/2., bar.get_height()/2,
                                                    '最快',
                                                    ha='center', va='center', fontsize=10, 
                                                    fontweight='bold', color='white', rotation=90)
                                    
                                    fig1.tight_layout()
                                    
                                    # 在选项卡中显示图表
                                    canvas1 = FigureCanvasTkAgg(fig1, master=perf_tab)
                                    canvas1.draw()
                                    canvas1.get_tk_widget().pack(fill=tk.BOTH, expand=True)
                                    
                                    # 2. 不同数据规模的性能比较（预测）- 美化版
                                    # ...existing code...
                                    
                                    # 3. 数据分布可视化 - 美化版
                                    dist_tab = ttk.Frame(charts_notebook)
                                    charts_notebook.add(dist_tab, text="数据分布")
                                    
                                    fig3 = plt.Figure(figsize=(6, 4), dpi=100)
                                    fig3.patch.set_facecolor('#f8f9fa')
                                    
                                    # 创建两个子图，但使用更现代的布局
                                    gs = fig3.add_gridspec(1, 2, hspace=0.1, wspace=0.15)
                                    ax3a = fig3.add_subplot(gs[0, 0])
                                    ax3b = fig3.add_subplot(gs[0, 1])
                                    
                                    ax3a.set_facecolor('#f8f9fa')
                                    ax3b.set_facecolor('#f8f9fa')
                                    
                                    # 限制显示的数据点数量
                                    sample_size = min(100, len(original_data))
                                    
                                    # 使用更有吸引力的散点图
                                    # 原始数据 - 蓝色阴影
                                    ax3a.scatter(range(sample_size), original_data[:sample_size], 
                                              alpha=0.6, s=30, c='#3498db', edgecolor='white')
                                    # 添加趋势线或曲线拟合
                                    try:
                                        z = np.polyfit(range(sample_size), original_data[:sample_size], 3)
                                        p = np.poly1d(z)
                                        ax3a.plot(range(sample_size), p(range(sample_size)), 
                                                "r--", linewidth=1, alpha=0.5)
                                    except:
                                        pass  # 如果拟合失败就忽略
                                        
                                    ax3a.set_title('原始数据分布', fontsize=12, fontweight='bold')
                                    ax3a.set_xlabel('索引', fontsize=10)
                                    ax3a.set_ylabel('值', fontsize=10)
                                    
                                    # 删除顶部和右侧边框
                                    ax3a.spines['top'].set_visible(False)
                                    ax3a.spines['right'].set_visible(False)
                                    
                                    # 排序后数据 - 绿色阴影
                                    ax3b.scatter(range(sample_size), sorted_data[:sample_size], 
                                              alpha=0.6, s=30, c='#2ecc71', edgecolor='white')
                                    # 添加趋势线
                                    ax3b.plot(range(sample_size), sorted_data[:sample_size], 
                                            linewidth=1, color='#27ae60', alpha=0.5)
                                            
                                    ax3b.set_title('排序后数据分布', fontsize=12, fontweight='bold')
                                    ax3b.set_xlabel('索引', fontsize=10)
                                    ax3b.set_ylabel('值', fontsize=10)
                                    
                                    # 删除顶部和右侧边框
                                    ax3b.spines['top'].set_visible(False)
                                    ax3b.spines['right'].set_visible(False)
                                    
                                    # 添加网格 - 使用虚线并降低不透明度使其不干扰主要数据
                                    ax3a.grid(True, linestyle='--', alpha=0.3)
                                    ax3b.grid(True, linestyle='--', alpha=0.3)
                                    ax3a.set_axisbelow(True) 
                                    ax3b.set_axisbelow(True)
                                    
                                    fig3.tight_layout()
                                    
                                    # 在选项卡中显示图表
                                    canvas3 = FigureCanvasTkAgg(fig3, master=dist_tab)
                                    canvas3.draw()
                                    canvas3.get_tk_widget().pack(fill=tk.BOTH, expand=True)
                                    break

def main():
    root = tk.Tk()
    app = SortingAlgorithmUI(root)
    root.mainloop()

if __name__ == "__main__":
    main()

